package com.jyu.hakkatranslation.controller;

import com.google.gson.Gson;
import com.jyu.hakkatranslation.dao.AnswerMapper;
import com.jyu.hakkatranslation.pojo.Answer;
import com.jyu.hakkatranslation.pojo.SingleWord;
import com.jyu.hakkatranslation.pojo.User;
import com.jyu.hakkatranslation.service.SingleWordService;
import com.jyu.hakkatranslation.vo.CommitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("users")
public class MuseumController {

    @Autowired
    AnswerMapper answerMapper;

    @Autowired
    SingleWordService singleWordService;

    @PostMapping("/commit")
    public String UserCommit(@RequestBody String  commit, HttpSession session){
        Gson gson = new Gson();
        CommitVo commitVo = gson.fromJson(commit, CommitVo.class);
        String context = commitVo.getUserAnswer();
        String src = commitVo.getMp3Id();
        Answer answer = new Answer();
        answer.setMp3Id(src.charAt(5)-'0');///mp3/1.mp3
        answer.setUserAnswer(context);
        //从session取出user
        User user = (User) session.getAttribute("user");
        //获取用户的id存入answer
        answer.setUserid(user.getId());
        System.out.println("用户id"+answer.getUserid());
//        Long touserid = (Long) session.getAttribute("user");
//        answer.setUserid(touserid);
//        System.out.println("用户id"+touserid);
        session.setAttribute("mp3Id",answer.getMp3Id());
        System.out.println(session.getAttribute("mp3Id"));
        answerMapper.insertUserAnswer(answer);
        String commit_successfully = gson.toJson("Commit Successfully");
        return commit_successfully;
    }

    @GetMapping("/SelectAll")
    public String SelectAll(){
//        List<Answer> answers = answerMapper.SelectAll();
        List<SingleWord> singleWords = singleWordService.SelectAllWord();
//        String returnString="音乐id,用户答案\n";
//        for (Answer answer : answers) {
//            returnString+=answer.getMp3Id()+",";
//            returnString+=answer.getUserAnswer();
//            returnString+="\n";
//        }
        String returnString="中文"+"读音"+"\n";
        for (SingleWord singleWord : singleWords) {
            returnString+=singleWord.getMandarin()+",";
            returnString+=singleWord.getPronunciation();
            returnString+="\n";
        }
        System.out.println(returnString);
        return returnString;
    }
}
